import { segment } from 'oicq'
import plugin from '../../../lib/plugins/plugin.js'
import Config from '../models/Config.js'
import fetch from 'node-fetch'

export class xy_poke extends plugin {
    constructor() {
        super({
            name: '小月戳一戳',
            dsc: '小月戳一戳',
            event: 'notice.group.poke',
            priority: 9999,
            rule: [{
                fnc: "poke",
            }]
        })
    }

    async poke(e) {
        if (!Config.getConfig().poke) return false
        const { pokeContent } = Config.getConfig()
        const roll = Math.random()
        if (roll < Config.getConfig().random) {
            if (pokeContent.image?.length > 0) {
                e.reply(segment.image(pokeContent.image[Math.floor(Math.random() * pokeContent.image.length)]))
                return true
            }
        } else if (roll < Config.getConfig().random + Config.getConfig().random_video) {
            if (pokeContent.video?.length > 0) {
                const video = pokeContent.video[Math.floor(Math.random() * pokeContent.video.length)]
                const res = await fetch(video)
                if (res.status === 302) {
                    const locationUrl = res.headers.get('Location')
                    if (locationUrl) {
                        res = await fetch(locationUrl)
                    } else {
                        logger.error("Location header not found in response.")
                        return false
                    }
                }
                if (!res.ok) {
                    logger.error(`Failed to fetch video: ${res.status}`)
                    return false
                }
                const arrayBuffer = await res.arrayBuffer()

                e.reply(segment.video(Buffer.from(arrayBuffer)))
                return true
            }
        } else if (roll < Config.getConfig().random + Config.getConfig().random_video + Config.getConfig().random_record) {
            if (pokeContent.record?.length > 0) {
                e.reply(segment.record(pokeContent.record[Math.floor(Math.random() * pokeContent.record.length)]))
                return true
            }
        } else {
            if (pokeContent.text?.length > 0) {
                e.reply(pokeContent.image[Math.floor(Math.random() * pokeContent.text.length)])
                return true
            }
        }
        return false
    }
}